package com.qf.servlet;

import com.qf.entity.Book;
import com.qf.service.impl.BookServiceImpl;
import com.qf.util.MyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 孙亚梅
 * @version V1.0
 * @Project bookApp-homework
 * @Package ${PACKAGE_NAME}
 * @Description: ${TODO}
 * @Date 2022/5/14 19:28
 */
@WebServlet(name = "AddBookServlet" ,urlPatterns = "/addBook")
public class AddBookServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        HttpSession session =request.getSession();

        //获取请求参数
        String bookname = request.getParameter("bookname");
        String author = request.getParameter("author");
        double price = Double.parseDouble(request.getParameter("price"));
        String description = request.getParameter("description");
        String publisher = request.getParameter("publisher");

        if (MyUtil.isEmpty(bookname)){
            session.setAttribute("msg", "书名不能为空");
            response.sendRedirect(request.getContextPath()+"/addBook.jsp");
            return;
        }
        if (MyUtil.isEmpty(author)){
            session.setAttribute("msg","作者不能为空");
            response.sendRedirect(request.getContextPath()+"/addBook.jsp");
            return;
        }
        Book book = new Book(null, bookname,price, description,  author, publisher);
        //调用业务层，将书籍添加到数据库中
        BookServiceImpl bookService = new BookServiceImpl();
        boolean result = bookService.addBook(book);

        if (result){
            //添加成功，显示新的列表
            response.sendRedirect(request.getContextPath()+"/bookList");
        }else {
            //添加失败，重新添加
            session.setAttribute("msg", "添加失败");
            response.sendRedirect(request.getContextPath()+"/addBook.jsp");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
